# -*- coding: utf-8 -*-

from django import forms
from django.forms import fields
from .models import Auth as AuthModel

# 模型表单
class AuthModelForm(forms.ModelForm):
    class Meta:
        model = AuthModel
        fields = ['username','password'] # 需校验字段
        exclude = []  # 不需要校验

        field_classes = {
            'username':forms.CharField,
            'password':forms.CharField,
        }
        labels = {
            'username':'用户名',
            'password':'密码'
        }

        widgets = {
            'username':forms.TextInput(
                attrs={'placeholder':'请输入用户名'}
            ),
            'password':forms.PasswordInput(
                attrs={'placeholder': '请输入密码'},
                render_value=True
            )
        }
        error_messages = {
            'username': {'required': '用户名不可以为空'},
            'password': {'min_length': '最爱哦不能低于10个字符'}
        }

        def clean_username(self):
            username = self.cleaned_data.get('username')

            if len(username) > 10:
                raise forms.ValidationError('用户名最大不可超过10')

            return username




# 后端回显前端
class Auth(forms.Form):
    username = fields.CharField(
        max_length=18,
        required=True,
        label="usename",
        widget=forms.TextInput(attrs={"placeholder":"最大不可超过18个字符"})
    )
    password = fields.CharField(
        widget=forms.PasswordInput(attrs={'placeholder':'最大不可超过18个字符'}),
        label="password",
        required=True,
        min_length=10,
        error_messages={'min_length':'最小不能低于10个字符'}

    )
   # 整体校验
    def clean(self):
        #username = self.cleaned_data.get('username','')
        password = self.cleaned_data.get('password','')

        if not password:
            raise forms.ValidationError('密码不可为空')

    # 单独校验
    def clean_username(self):
        print('username',self.cleaned_data)
        username = self.cleaned_data.get('username',"")
        if len(username) >5:
            raise forms.ValidationError("用户名最大不能超过5")
        return username

